
#include "net.h"

int main()
{

	int fd = -1;
	struct sockaddr_in soc;

	/* 1.创建套接字 */
	if(( fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("socket");
		exit(1);
	}

	/* 2.绑定 */
	soc.sin_family = AF_INET;
	soc.sin_port = htons(PORT);
	/* 绑定任何ip地址 */
	soc.sin_addr.s_addr =htonl(INADDR_ANY);

	/* bind绑定 */
	if(( bind(fd, (struct sockaddr *)&soc, sizeof(soc))) < 0)
	{

		perror("bind");
		exit(1);
	}

	/* 把主动变成被动 */
	if( (listen(fd, BACKLOG)) < 0)
	{
		perror("listen");
		exit(1);
	}
	printf("服务器启动\n");

	/* 阻塞等待连接*/
	/* 通过程序获得刚建立连接的socket的客户端ip地址和端口号 */
	struct sockaddr_in sin;
	socklen_t soklen = sizeof(sin);
	int newfd = -1;
	if( (newfd = accept(fd, (struct sockaddr*)&sin, &soklen)) < 0)
	{
		perror("accept");
		exit(1);
	}

	char ipv4[16];
	if(inet_ntop(AF_INET, (void* )&sin.sin_addr, ipv4, sizeof(sin)) < 0)
	{
		perror("ntop");
		exit(0);
	}
	printf("连接的客户端ipv4:%s 端口号:%d\n",ipv4, ntohs(sin.sin_port));

	printf("服务器连接\n");

	/* 读写数据 */
	int ret = -1;
	char buf[BUFSI];
	while(1)
	{
		bzero(buf, BUFSI);
		do
		{	/* 遇到中断的情况继续读 */
			ret = read(newfd, buf, BUFSI-1 );
		}while(ret<0 && errno == EINTR);
		if(ret < 0)
		{
			perror("read");
			exit(1);
		}
		if(!ret)
		{
			break; /* 客户端关闭了 */
		}
		printf("read data: %s", buf);		/*  打印读到的信息 */

		if (!strncasecmp (buf, QUIT, strlen (QUIT))) {	//用户输入了quit字符
			printf ("Client is exiting!\n");
			break;
		}
	}
}



























